<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="pragma" content="no-cache"/>   
<meta http-equiv="Cache-Control" content="no-cache, must-revalidate"/>   
<meta http-equiv="expires" content="0"/>  
<title>角色分配</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="css/select.css" rel="stylesheet" type="text/css" />
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery.idTabs.min.js"></script>
<script type="text/javascript" src="js/select-ui.min.js"></script>
<script type="text/javascript" src="editor/kindeditor.js"></script>


  
<script type="text/javascript">

var roles = {};
function detail(id){
	//alert(JSON.stringify(roles));
	var role = roles[id];
	$("INPUT[name='roleName']").val(role.roleName);
	//$("DIV[name='roleAddForm'").find("INPUT").attr("disabled",true);
	$("#roleOperator").html("编辑");
	$("#btnSave").unbind();
	$("#btnSave").click(function(){
		var currentRole = roles[id];
		var roleName = $("input[name='roleName']").val();
		if(null == roleName || "" == roleName){
		    alert("请输入角色类型");
		    return false;
		}
		currentRole["roleName"] = roleName;
		updateRole(currentRole);
	});

	$("INPUT[functionId]").prop({checked:false});
	$.each(role.functions,function(index,fun){
		$("INPUT[functionId='"+fun.functionId+"']").prop({checked:true});
	});
	$("INPUT[admin]").prop({checked:false});
	$.each(role.admins,function(index,admin){
		$("INPUT[admin='"+admin+"']").prop({checked:true});
	});
	$("DIV[name='roleShowList']").hide();
	$("DIV[name='roleAddForm']").show();
}

function addRole(){
	$("INPUT[name='roleName']").val("");
	$("INPUT[type=checkbox]").prop({checked:false});	
	$("#roleOperator").html("添加");
	$("#btnSave").unbind();
	$("#btnSave").click(saveRole);
	$("DIV[name='roleShowList']").hide();
	$("DIV[name='roleAddForm']").show();	
}

function deleteRole(id){
	 if(confirm("确定删除该角色?")){
		var requestJson = {id:id};
		$.ajax({
	        url: '/euc/role/delete',
	        data:JSON.stringify(requestJson),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	var cur = $('.paginItem.current').find("a").html();
				cur = parseInt(cur);
				search(cur);
				alert(result.message);
	        },
	        error: function () {
	        	console.log("error");
	        }  
	    });
	 }
}

var pageBean = null;
function initailPageNumber(totalPage,currentPage,pageLength){				
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){
					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){/*alert(e.messge);*/}	
}


function search(currentPage){			
	var parameter = $("#managerListSelect").val();//$("INPUT[name='parameter']").val();
	var requestJson = {currentPage:currentPage,data:{"roleName":parameter}};
	$.ajax({
        url: '/euc/role/query',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
        	pageBean = result.data;
        	$("#roleTable").empty();	        	
        	$.each(result.data.list,function(i,data){
        		var html = '<tr>';
        		html += '<td style="width:5%;min-width:40px;">' + (i+1) + '</td>';
        		html += '<td style="width:20%;">' + data.roleName + '</td>';
        		html += '<td style="width:50%;">' + data.functionNames + '</td>';
        		html += '<td style="width:15%;">' + data.createTime + '</td>';
        		html += '<td style="width:15%;"><a href="javascript:detail('+data.id+');" class="tablelink">查看</a>&nbsp;&nbsp;&nbsp;<a href="javascript:deleteRole('+data.id+');" class="tablelink">删除</a></td>';
        		html += '</tr>';
	        	$("#roleTable").append(html);
	        	roles[data.id] = data;
			});
        	
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	console.log("error");
        }  
    });
}

$(document).ready(function(e) {			
    $(".select1").uedSelect({
		width : 345			  
	});
	$(".select2").uedSelect({
		width : 167  
	});
	$(".select3").uedSelect({
		width : 100
	});		
	$("#add").click(addRole);
	search(1);

    initailRoleTypeSelect();
});

function initailRoleTypeSelect(){
    $.ajax({
        url: '/euc/role/type',
        data:'',
        beforeSend: function(request) {
            var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
            //alert(JSON.stringify(result));
            $(".select1").empty();
            $('<option value="" selected>请选择</option>').appendTo($(".select1"));
            $.each(result,function(index,role){
                $('<option value="'+ role.roleName +'">'+ role.roleName +'</option>').appendTo($(".select1"));
            });
            $(".select1").val("").trigger("change");
        },
        error: function () {
            alert("error");
        }
    });
}
</script>
</head>

<body>

	<div class="place" name="roleShowList">
    	<span>位置：</span>
    	<ul class="placeul">
		    <li><a href="#">权限管理</a></li>
		    <li><a href="/euc/page/roleList.html">角色</a></li>
    	</ul>
    </div>
    
    <div class="formbody" name="roleShowList">
    
    <div class="tools">    
    	<ul class="toolbar">
	        <li class="click" id="add"><span><img src="images/t01.png" /></span>添加</li>
        </ul>
        <ul class="seachform">  
	    	<!--<li><label>&nbsp;&nbsp;&nbsp;&nbsp;综合查询</label><input  name="parameter" type="text" class="scinput"  placeholder="用户名/ 姓名/ 手机号"/></li>-->
			<li>
				<label>&nbsp;&nbsp;&nbsp;&nbsp;角色类型：</label>
				<div class="vocation">
					<select class="select1" id="managerListSelect">
						<option value="" selected>请选择</option>
					</select>
				</div>
			</li>
			<li><label>&nbsp;</label><input name="" onclick="search(1);" type="button" class="scbtn" value="查询"/></li>
	    </ul>
    </div>
    
    
    <div id="usual1" class="usual"> 
  	
  	<div id="tab2" class="tabson">
    
	<table class="tablelist">
    	<thead>
	    	<tr>
		        <th>序号</th>
		        <th>角色类型<i class="sort"><img src="images/px.gif" /></i></th>
		        <th>权限</th>
		        <th>创建时间</th>
		        <th>操作</th>
	        </tr>
        </thead>
        <tbody id="roleTable">
        <!-- 
	        <tr>
		        <td><input name="" type="checkbox" value="" /></td>
		        <td>20130908</td>
		        <td>王金平幕僚：马英九声明字字见血 人活着没意思</td>
		        <td>admin</td>
		        <td>江苏南京</td>
		        <td>2013-09-09 15:05</td>
		        <td>已审核</td>
		        <td><a href="#" class="tablelink">查看</a>     <a href="#" class="tablelink"> 删除</a></td>
	        </tr> 
	    -->
        </tbody>
    </table>
    
    
    <div class="pagin">    
    	<div class="message">共<i id="totalRow" class="blue">0</i>条记录，每页<i id="pageSize" class="blue">2&nbsp;</i>条记录，当前显示第&nbsp;<i id="currentPage" class="blue">2&nbsp;</i>页</div>
        <ul class="paginList" >
	        <li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>
	        <li class="paginItem"><a href="javascript:;">1</a></li>
	        <li class="paginItem current"><a href="javascript:;">2</a></li>
	        <li class="paginItem more"><a href="javascript:;">...</a></li>
	        <li class="paginItem"><a href="javascript:;">4</a></li>
	        <li class="paginItem"><a href="javascript:;">5</a></li>
	        <li class="paginItem"><a href="javascript:;">6</a></li>
	        <li class="paginItem"><a href="javascript:;">7</a></li>
	        <li class="paginItem"><a href="javascript:;">8</a></li>
	        <li class="paginItem"><a href="javascript:;">9</a></li>
	        <li class="paginItem"><a href="javascript:;">10</a></li>
	        <li class="paginItem more"><a href="javascript:;">...</a></li>
	        <li class="paginItem"><a href="javascript:;">110</a></li>
	        <li class="paginItem"><a href="javascript:;">111</a></li>
	        <li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>
        </ul>
    </div>	
   
  
    
    </div>  
       
	</div> 
 
		<script type="text/javascript"> 
	      	$("#usual1 ul").idTabs(); 
	    </script>
	    
	    <script type="text/javascript">
			$('.tablelist tbody tr:odd').addClass('odd');
		</script>    
    </div>

	<div class="place" name="roleAddForm" style="display: none">
	    <span>位置：</span>
	    <ul class="placeul">
	    <li><a href="#">权限管理</a></li>
	    <li><a href="/euc/page/roleList.html">角色</a></li>
	    <li><a href="#" id="roleOperator">添加</a></li>
	    </ul>
	    </div>
	    
	    <div class="formbody" name="roleAddForm" style="display: none">
	    
	    <div class="formtitle"><span>角色信息</span></div>
	    
	    <ul class="forminfo">
		    <li><label style="font-size:16px;margin-top:0px;">角色类型</label><input name="roleName" type="text" class="dfinput" /><i>输入角色类型，如运营管理员，财务管理员</i></li>
		    <li id="roleHeader">
		    	<label style="font-size:16px;margin-top:-5px;">角色权限</label>
		    	<p style="font-size:16px;"><input name="" type="checkbox"/>&nbsp;&nbsp;全部权限</p>
				<div class="divLine"></div>
			</li>
			<!-- 
			    <li>
			    	<label style="font-size:16px;margin-top:-5px;">&nbsp;</label>
			    	<p style="font-size:16px;">
			    		<input name="" type="checkbox"/>&nbsp;&nbsp;招商管理&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
			    		<input name="" type="checkbox"/>&nbsp;&nbsp;管理员
			    	</p>
		   		</li>
		   		<li>
			    	<label style="font-size:16px;margin-top:-5px;">&nbsp;</label>
			    	<p style="font-size:14px;">
			    		<input name="" type="checkbox"/>&nbsp;&nbsp;全部权限&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
			    		<input name="" type="checkbox"/>&nbsp;&nbsp;全部权限
			    	</p>
		   			<div class="divLine"></div>
		   		</li>
	 		-->
		    <li>
		    	<label>&nbsp;</label>
		    	<input name="btnSave"  id="btnSave"  type="button" class="btn" value="确定"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		    	<input name="btnCancle"  id="btnCancle"  type="button" class="btn" value="取消"/>
		    </li>
	    </ul>
    </div>
<script type="text/javascript">

function updateRole(role){	
	//alert(JSON.stringify(role));
	var admins = [];
	$("INPUT[admin]:checked").each(function(index,admin){
		var adminId = $(admin).attr('admin');
		admins[index]= adminId;
	});
	role["admins"]=admins;
	
	var functions = [];
	$("INPUT[functionId]:checked").each(function(index,element){
		try{
			var functionId = $(element).attr("functionId")
			var fun = allFunctionMap[functionId];
			if($("INPUT[parentId='"+functionId+"']").length <= 0){
				$.each(fun.children,function(i,childFunction){
					if(childFunction.functionId == '1110'){
						var adminChecked = $("INPUT[admin='10000']:checked").length;
						if(adminChecked > 0){
							functions.push(childFunction);
						}
					}else{
						functions.push(childFunction);
					}					
				});
			}
			functions.push(fun);
		}catch(e){/*alert(e.message);*/}
	});
	role["functions"] = functions;
	$.ajax({
        url: '/euc/role/update',
        data:JSON.stringify(role),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	console.log(JSON.stringify(result));
        	if(result.status == '0'){
        		$("DIV[name='roleShowList']").show();
    			$("DIV[name='roleAddForm']").hide();
            	search(pageBean.currentPage);
        	}else{
        		alert(result.message);
        	}
        },
        error: function () {
        	console.log("error");
        }
    });
}

function saveRole(){	
	//alert(JSON.stringify(allFunctionMap));
	var roleName = $("INPUT[name='roleName']").val();
	if($.trim(roleName) == ''){
		alert("请输入角色类型");
		return;
	}
	var admins = [];
	$("INPUT[admin]:checked").each(function(index,admin){
		var adminId = $(admin).attr('admin');
		admins[index]= adminId;
	});
	
	var requestJson = {roleName:roleName,roleType:roleName};
	var functions = [];
	$("INPUT[functionId]:checked").each(function(index,element){
		try{
			var functionId = $(element).attr("functionId")
			var fun = allFunctionMap[functionId];
			if($("INPUT[parentId='"+functionId+"']").length <= 0){
				$.each(fun.children,function(i,childFunction){
					functions.push(childFunction);
				});
			}
			functions.push(fun);
		}catch(e){/*alert(e.message);*/}
	});
	requestJson["functions"] = functions;
	requestJson["admins"]=admins;
	$.ajax({
        url: '/euc/role/add',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	console.log(JSON.stringify(result));
        	if(result.status == '0'){
        		$("DIV[name='roleShowList']").show();
    			$("DIV[name='roleAddForm']").hide();
            	search(pageBean.currentPage);
        	}else{
        		alert(result.message);
        	}
        },
        error: function () {
        	console.log("error");
        }
    });
	
}

function cancle(){
	$("DIV[name='roleShowList']").show();
	$("DIV[name='roleAddForm']").hide();
}

var allFunctionMap = {};
function initialRoleForm(){
	 $.ajax({
	        url: '/euc/function/all',
	        data:"",//JSON.stringify(requestData),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (datas, textStatus, response) {
	        	var allFunctions = JSON.stringify(datas);
	        	localStorage.setItem("allFunctions", allFunctions);
	        	$.each(datas,function(i,data){
	        		if(data.functionId == '80000'){//跳过个人中心
	        			return true;
	        		}
	        		allFunctionMap[data.functionId] = data;
	        		var parent_li = $('<li><label style="font-size:16px;margin-top:-5px;">&nbsp;</label></li>');
	        		var parent_menu_string = '<p style="font-size:16px;">';
	        		parent_menu_string    += '<input parentId="'+ data.parentId +'" functionId="'+data.functionId+'" name="" menu type="checkbox"/>&nbsp;&nbsp;'+data.functionName+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	        		parent_menu_string    += '<input admin="'+data.functionId+'" name="" type="checkbox"/>&nbsp;&nbsp;管理员';
	        		parent_menu_string    += '</p>';
	        		$(parent_menu_string).appendTo($(parent_li));
	        		$(parent_li).appendTo($("#roleHeader"));
	        		
	        		var childLi = $('<li><label style="font-size:16px;margin-top:-5px;">&nbsp;</label></li>');
	        		var menuContainer = '<p style="font-size:16px;"></p>';
	        		var divLine = '<div class="divLine"></div>';
	        		$.each(data.children,function(i,child){ 
	        			allFunctionMap[child.functionId] = child;
	        			menuContainer += '<input parentId="'+ data.functionId +'" functionId="'+child.functionId+'" name="" menu type="checkbox"/>&nbsp;&nbsp;'+child.functionName+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	        		});
	        		menuContainer += '</p>';
	        		$(menuContainer).appendTo($(childLi));
	        		$(divLine).appendTo($(childLi));
        			$(childLi).appendTo($("#roleHeader"));
				});
        		$("INPUT[type=checkbox][functionId]").change(function(){
        			$("INPUT[type=checkbox][parentId='"+$(this).attr("functionId")+"']").prop({checked:$(this).is(':checked')});		
        		});
	        },
	        error: function () {
	        	console.log("error");
	        }
	    });
	
}

$(document).ready(function(e) {	
	$("#btnSave").click(saveRole);
	$("#btnCancle").click(cancle);
	$("INPUT[type=checkbox]").change(function(){
		$("INPUT[type=checkbox][functionId]").prop({checked:$(this).is(':checked')});		
	});
	initialRoleForm();	 
});
</script>
</body>
</html>
